/*
 * @Author: ItKui
 * @Date: 2020-08-06 15:18:40
 * @LastEditTime: 2020-08-06 17:48:59
 * @FilePath: \cpyj-website\gulpfile.js
 */
const { src, dest, series, parallel, watch } = require('gulp');
const $ = require('gulp-load-plugins')(); // gulp自动加载

function clean() {
  return src('./dist', { read: false }).pipe($.clean()).pipe($.livereload());
}

function preCss3() {
  return src('./src/css/*.css')
    .pipe(
      $.autoprefixer({
        browsers: ['last 2 versions', 'Android >= 4.0'],
        cascade: true,
      }),
    )
    .pipe($.cleanCss())
    .pipe($.rev())
    .pipe(dest('./dist/css'))
    .pipe($.livereload());
}

function es6ToEs5() {
  return src('./src/js/*.js')
    .pipe(
      $.babel({
        presets: ['@babel/env'],
      }),
    )
    .pipe($.uglify())
    .pipe($.rev())
    .pipe(dest('./dist/js'))
    .pipe($.livereload());
}

function compileHtml() {
  var sources = src(['./dist/css/*.css', './dist/js/*.js'], { read: false });
  return src('./src/index.html')
    .pipe($.inject(sources))
    .pipe($.htmlmin())
    .pipe(dest('./dist'))
    .pipe($.livereload());
}

function connect() {
  $.connect.server({
    root: './src',
    livereload: true,
  });
}

function html() {
  return src('/src/index.html')
    .pipe(dest('/dest/index.html'))
    .pipe($.connect.reload());
}

function dev() {
  watch(['/src/**/*.*'], html);
}

exports.build = series(clean, parallel(preCss3, es6ToEs5), compileHtml);
exports.dev = series(html, connect, dev);
